﻿using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketCore.Domain.Account;

namespace WebSocketCore.Domain.Entities
{
    public class WebSocketEntity : INotify
    {
        public IUser User { get; set; }
        public WebSocket WebSocket { get; set; }
        public static WebSocketEntity Create(IUser user, WebSocket webSocket)
        {
            return new WebSocketEntity() { User = user, WebSocket = webSocket };
        }
        public async Task NotifyAsync(MessageEntity msg)
        {
            if (WebSocket == null)
            {
                throw new ArgumentNullException($"用户:{msg.From} webSocket为null");
            }

            if (WebSocket.State == WebSocketState.Open)
            {
                byte[] bts = Encoding.UTF8.GetBytes($"{msg.From}:{msg.Message}");
                await WebSocket.SendAsync(new ArraySegment<byte>(bts), WebSocketMessageType.Text, true, CancellationToken.None);
            }
            else
            {

            }
        }
    }
}
